﻿using CaseManagerLibrary.Http;
using CaseManagerLibrary.Models;
using Newtonsoft.Json;
using PSDLib.Models;
using SDDLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace PSDClientService.SystemSettings
{
    public class Setting
    {
        private const string settingFolder = "PSD";
        private const string settingFile = "psdsettings.json";

        public string ApiServerAddress { get; set; }
        public string TcpServerAddress { get; set; }
        public int TcpServerPort { get; set; }
        public int TcpListenerPort { get; set; } = 11981;
        public int PSDListenPort { get; set; }
        public int PSDSendPort { get; set; }
        public int MaxDownloadProcess { get; set; }
        public int DeviceConnectType { get; set; }
        public string DownloadDataPath { get; set; }
        public double StorageAvailablePercent { get; set; }
        public string LogType { get; set; }
        public string LogPath { get; set; }
        public string DeviceVersion { get; set; }
        public string PWD { get; set; }
        public int BurnListenPort { get; set; }
        public int BurnSendPort { get; set; }
        public int RecorderCount { get; set; }
        public int DownloadKeepAliveTimeout { get; set; } = 10;
        public string CaseLogDownloadTime { get; set; } = "00:01";
        public string[] DeviceRebootTime { get; set; } = new string[] { "07:30", "19:30" };
        public int DisconnectServerTimeout { get; set; } = 5;
        public int MaxCrashRebootTimes { get; set; } = 3;
        public string PemFile { get; set; }

        [JsonIgnore]
        public string DefaultPassword { get; set; }
        [JsonIgnore]
        public string DefaultSalt { get; set; }
        [JsonIgnore]
        public string DownloadServerIP { get; set; }
        [JsonIgnore]
        public ushort DownloadServerPort { get; set; }
        [JsonIgnore]
        public string DownloadServerUserId { get; set; }
        [JsonIgnore]
        public string DownloadServerPwd { get; set; }
        [JsonIgnore]
        public API API { get; set; }

        public bool Read()
        {
            bool success = false;

            API = new API();

            try
            {
                string file = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), settingFolder, settingFile);
                bool exist = System.IO.File.Exists(file);

                if (exist)
                {
                    string json = System.IO.File.ReadAllText(file);
                    var setting = JsonConvert.DeserializeObject<Setting>(json);

                    ApiServerAddress = setting.ApiServerAddress;
                    TcpServerAddress = setting.TcpServerAddress;
                    TcpServerPort = setting.TcpServerPort;
                    TcpListenerPort = setting.TcpListenerPort;
                    PSDListenPort = setting.PSDListenPort;
                    PSDSendPort = setting.PSDSendPort;
                    LogType = setting.LogType;
                    LogPath = setting.LogPath;
                    StorageAvailablePercent = setting.StorageAvailablePercent;
                    MaxDownloadProcess = setting.MaxDownloadProcess;
                    DeviceConnectType = setting.DeviceConnectType;
                    DownloadDataPath = setting.DownloadDataPath;
                    DeviceVersion = setting.DeviceVersion;
                    PWD = setting.PWD;
                    BurnListenPort = setting.BurnListenPort;
                    BurnSendPort = setting.BurnSendPort;
                    RecorderCount = setting.RecorderCount;
                    DownloadKeepAliveTimeout = setting.DownloadKeepAliveTimeout;
                    CaseLogDownloadTime = setting.CaseLogDownloadTime;
                    DeviceRebootTime = setting.DeviceRebootTime;
                    DisconnectServerTimeout = setting.DisconnectServerTimeout;
                    MaxCrashRebootTimes = setting.MaxCrashRebootTimes;
                    PemFile = setting.PemFile;

                    foreach (var p in API.GetType().GetProperties())
                    {
                        p.SetValue(API, ApiServerAddress + "api/VideoDownload/" + p.Name);
                    }

                    success = true;
                }
                else
                {
                    success = false;
                }
            }
            catch (Exception ex)
            {
                success = false;
            }

            return success;
        }

        public void Update()
        {
            var result_config = HttpHelper.Get<HResult<dl_device_default_config>>(API.GetDownloadDeviceDefaultConfig);
            dl_device_default_config defaultConfig = null;

            if (result_config.success && result_config.data != null)
            {
                defaultConfig = result_config.data;
            }
            else
            {
                defaultConfig = GetDefaultConfig();
            }

            DefaultPassword = defaultConfig.device_pwd;
            DefaultSalt = defaultConfig.device_pwd_salt;

            if (PSDListenPort == 0)
            {
                PSDListenPort = defaultConfig.psd_listen_port;
            }
            if (PSDSendPort == 0)
            {
                PSDSendPort = defaultConfig.psd_send_port;
            }
            if (MaxDownloadProcess == 0)
            {
                MaxDownloadProcess = defaultConfig.max_download_process;
            }
            if (StorageAvailablePercent == 0)
            {
                StorageAvailablePercent = defaultConfig.storage_available_percent;
            }
            if (BurnListenPort == 0)
            {
                BurnListenPort = defaultConfig.burn_listen_port;
            }
            if (BurnSendPort == 0)
            {
                BurnSendPort = defaultConfig.burn_send_port;
            }
            if (RecorderCount == 0)
            {
                RecorderCount = defaultConfig.recorder_count;
            }
            if (string.IsNullOrEmpty(LogPath))
            {
                LogPath = defaultConfig.log_path;
            }
            if (string.IsNullOrEmpty(DownloadDataPath))
            {
                DownloadDataPath = defaultConfig.download_data_path;
            }
            if (string.IsNullOrEmpty(LogType))
            {
                LogType = "sql";
            }
            Save();
        }

        private dl_device_default_config GetDefaultConfig()
        {
            var defaultConfig = new dl_device_default_config();
            defaultConfig.id = Guid.NewGuid().ToString();
            defaultConfig.psd_listen_port = 11982;
            defaultConfig.psd_send_port = 11983;
            defaultConfig.burn_listen_port = 11986;
            defaultConfig.burn_send_port = 11987;
            defaultConfig.recorder_count = 2;
            defaultConfig.max_download_process = 1;
            defaultConfig.download_data_path = "案件录像";
            defaultConfig.log_path = @"C:\PSDLog";
            defaultConfig.device_connect_type = 1;
            defaultConfig.device_pwd = "cXpqdw==";
            defaultConfig.device_pwd_salt = "hlTlulo5XuDjBc8PfqSNQw==";
            return defaultConfig;
        }

        public bool Save()
        {
            bool success = false;

            try
            {
                string path = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), settingFolder);

                string json = JsonConvert.SerializeObject(this, Formatting.Indented);

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                System.IO.File.WriteAllText(System.IO.Path.Combine(path, settingFile), json);

                success = true;
            }
            catch (Exception ex)
            {
                success = false;
            }

            return success;
        }
    }
}
